const errorTypes = require('../constants/error-types.js')
const md5password = require('../utils/password-handle');
const { PUBLIC_KEY } = require('../app/config');
const verifyUser = async (ctx, next) => {
  // 获取用户名和密码
  const { account, password } = ctx.request.body;

  // 判断用户名或者密码不能为空
  if (!account || !password) {
    const error = new Error(errorTypes.NAME_OR_PASSWORD_IS_REQUIRED);
    // 发送一个错误信息
    return ctx.app.emit('error', error, ctx);
  }

  await next();
};

const handlePassword = async (ctx, next) => {
  let { password } = ctx.request.body;
  ctx.request.body.password = md5password(password);

  await next();
}

const verifyLogin = async (ctx, next) => {
  // 获取token
  const authorization = ctx.headers.authorization;

  if (!authorization) {
    const error = new Error(errorTypes.UNAUTHRIZATION);
    return ctx.app.emit('error', error, ctx);
  }
  const token = authorization.replace("Bearer ", "");

  // 验证token (id/name/exp)
  try {
    // 可以解析出携带的payload
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ["RS256"]
    });
    ctx.user = result;
    await next();
  } catch (err) {
    const error = new Error(errorTypes.UNAUTHRIZATION);
    ctx.app.emit('error', error, ctx);
  }

  // 
}


module.exports = {
  verifyUser,
  handlePassword,
  verifyLogin
}